package com.ssy.invoicing.common.util;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Comment of FileUtil
 * @author suoyao.shen
 */
public class FileUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    
	/**
	 * write download file to outputstream
	 * @param downloadFileName
	 * @param file
	 * @param request
	 * @param response
	 * @throws Exception
	 */
    public static void writeDownloadFile(String downloadFileName, File file,
                                         HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        InputStream in = null;
        OutputStream out = null;
        try {

            String userAgent = request.getHeader("User-Agent");

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-msdownload;");

            // 这里要对不同的浏览器做不同的处理，防止文件名出现乱码
            if (userAgent != null && userAgent.indexOf("Firefox") > 0) {
                response.setHeader("Content-Disposition", "attachment; filename="
                        + new String(downloadFileName.getBytes("UTF-8"), "ISO8859-1"));
            } else {
                response.setHeader("Content-Disposition", "attachment; filename="
                        + new String(
                                URLEncoder.encode(downloadFileName, "UTF-8").getBytes("UTF-8"),
                                "GBK"));
            }

            in = new FileInputStream(file);
            out = new BufferedOutputStream(response.getOutputStream());

            IOUtils.copy(in, out);
        } catch (IOException e) {
            throw new Exception("download.fail");
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }
            if (out != null) {
                IOUtils.closeQuietly(out);
            }
        }
    }
    
    /**
     * 拷贝文件
     * @author suoyao.shen
     * @param sourcePath
     * @param destPath
     */
    public static void copyFile(String sourcePath, String destPath) {
        File directory = new File(sourcePath);
        if (directory.isDirectory()) {
            File[] files = directory.listFiles();
            for (File f : files) {
                if (f != null) {
                    copyFile(sourcePath + File.separator + f.getName(),destPath);
                }
            }
        } else {
            //copy file
            byte[] buffer = new byte[2048];
            int length = 0;
            try {
                FileInputStream in = new FileInputStream(new File(sourcePath));
                FileOutputStream out = new FileOutputStream(new File(destPath + File.separator + directory.getName()));
                while((length = in.read(buffer)) != -1 ) {
                    out.write(buffer, 0, length);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    /**
     * 读取TXT文件中的内容
     * @author suoyao.shen
     * @param txtSb
     * @param path
     */
    public static void readTxt(StringBuffer txtSb,String path) {
        String txt = "";
        FileReader reader = null;
        BufferedReader bufferR = null;
        try {
            reader = new FileReader(path);
            bufferR = new BufferedReader(reader);
            while((txt = bufferR.readLine()) != null) {
                txtSb.append(txt).append("\r\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferR != null) {
                    bufferR.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                logger.error("close BufferedReader and FileReader failed.",e);
            }
        }
    }
    
    /**
     * 将内容写入到txt文本中去
     * @author suoyao.shen
     * @param file
     * @param content
     */
    public static void writeTxt(File file,String[] content) {
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(file));
            for (String str : content) {
                bw.write(str + "\r\n");
            }
        } catch (IOException e) {
            logger.error("write txt file failed.",e);
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.flush();
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
}
